/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.yunhoo.pay.bean;

import com.ibatis.dao.client.DaoManager;
import com.yunhoo.asset.util.PayCodeConstants;
import com.yunhoo.base.bean.FinancialProjectBean;
import com.yunhoo.base.db.dao.DepartmentDao;
import com.yunhoo.base.db.dao.FinancialProjectDao;
import com.yunhoo.base.db.dao.PersonDao;
import com.yunhoo.base.db.impl.BusinessParameterImpl;
import com.yunhoo.pay.db.impl.AbroadGroupImpl;
import com.yunhoo.base.model.Department;
import com.yunhoo.base.model.FinancialProject;
import com.yunhoo.base.model.PayStyle;
import com.yunhoo.base.model.Person;
import com.yunhoo.pay.db.impl.LoanBillImpl;
import com.yunhoo.pay.db.impl.VoucherPubImpl;
import com.yunhoo.pay.model.Expense;
import com.yunhoo.pay.model.QueryVouchers;
import com.yunhoo.pay.model.VouCheckInfo;
import com.yunhoo.sys.db.config.DaoConfig;
import com.yunhoo.sys.db.util.IbatisTemplate;
import com.yunhoo.sys.util.common.Disabled;
import com.yunhoo.sys.util.common.LoginParam;
import com.yunhoo.sys.util.common.MoneyUtil;
import com.yunhoo.sys.util.common.NavigationTool;
import com.yunhoo.sys.util.common.Null;
import com.yunhoo.sys.util.common.ToolKit;
import com.yunhoo.sys.login.LoginBean;
import com.yunhoo.sys.util.tree.TreeUtil;


import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import javax.faces.event.ActionEvent;
import javax.faces.event.ValueChangeEvent;
import javax.faces.model.DataModel;
import javax.faces.model.ListDataModel;
import javax.faces.model.SelectItem;
import javax.servlet.ServletContext;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import net.sf.jasperreports.engine.JRExporterParameter;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.export.JRPdfExporter;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFooter;
import org.apache.poi.hssf.usermodel.HSSFHeader;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.CreationHelper;
import org.richfaces.component.UIDataTable;
import java.io.ByteArrayOutputStream;
import java.io.OutputStream;
import java.io.Serializable;
import java.sql.SQLException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import org.richfaces.event.TreeSelectionChangeEvent;

@ManagedBean(name = "loan")
@SessionScoped
public class LoanInputBean implements Serializable {

    private List<Expense> expenselist;
    private DataModel<Expense> expenseModel = new ListDataModel<Expense>();
    private LinkedList<Expense> linkedli = new LinkedList<Expense>();
    private QueryVouchers qlb = new QueryVouchers();
    private int index;
    private Expense exp = new Expense();
    private UIDataTable personData = null;
    private UIDataTable deptData = null;
    private boolean addOrUpdate = false;
    private boolean showAble = true;
    private boolean deleteable = false;
    private boolean saveOrNot = false;
    private boolean updateOrNot = false;
    private boolean submitOrNot = true;
    private boolean printAble = false;
    private boolean browAble = false;
    private Disabled dis = new Disabled();
    private List<SelectItem> payStyleli = null;
    private List<Department> deptli = null;
    //
    private static String nameSpace = "loanbill.";
    private static DaoManager daom;
    private static DepartmentDao dao;
    private static FinancialProjectDao finProjdao;
    private FinancialProject finProj = null;
    private DataModel<FinancialProject> finProjModel = null;
    private String projParam = "";
    private List<SelectItem> perli = null;
    private static PersonDao perDao;

    public LoanInputBean() {
        daom = DaoConfig.getDaoManager();
        dao = (DepartmentDao) daom.getDao(DepartmentDao.class);
        finProjdao = (FinancialProjectDao) daom.getDao(FinancialProjectDao.class);
        perDao = (PersonDao) daom.getDao(PersonDao.class);
        initStatus();
        initPayStyleList();
        initFinProjList();//预算项目列表
        //initDate();
    }

    private void initDate() {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        calendar.add(Calendar.DAY_OF_MONTH, -10);
        Date begin = calendar.getTime();
        Date end = new Date();
        qlb.setNumDateStart(begin);
        qlb.setNumDateEnd(end);
    }

    public final void initStatus() {
        saveOrNot = true;
        addOrUpdate = false;
        deleteable = true;
        updateOrNot = true;
        submitOrNot = true;
        showAble = true;
        printAble = true;
        initList();
    }

    private void initList() {
        linkedli = new LinkedList();
        Map map = new HashMap();
        map.put("cpsn_number", curPerNum().trim());
        map.put("orgCode", curOrgCode().trim());
        expenselist = IbatisTemplate.queryForList(nameSpace + "queryLoanBillByPersonName", map);
        linkedli.addAll(expenselist);
    }

    public final void initPayStyleList() {
        payStyleli = new ArrayList();
        List<PayStyle> Styleli = AbroadGroupImpl.getPaystyleliNew("3");
        for (PayStyle d : Styleli) {
            payStyleli.add(new SelectItem(d.getCode(), d.getName()));
        }
    }

    //选择部门
    public void selected(TreeSelectionChangeEvent event) {
        Department dp = (Department) TreeUtil.listener(event);
        exp.getPayDept().setCode(dp.getCode());
        exp.getPayDept().setName(dp.getName());
//        if (!Null.check(exp.getPayDept().getCode())) {
//            queryPerLi();
//        }
    }

    private void queryPerLi() {
        perli = new ArrayList<SelectItem>();
        List<Person> templi = null;
        try {
            Person param = new Person();
            param.setOrgCode(curOrgCode());
            param.setIyear(curIyear());
            param.setDeptCode(exp.getPayDept().getCode());
            //templi = perDao.queryListByDept(param);
            templi = perDao.queryAll();
        } catch (SQLException ex) {
            Logger.getLogger(LoginBean.class.getName()).log(Level.SEVERE, null, ex);
        }
        if (templi != null) {
            for (Person p : templi) {
                perli.add(new SelectItem(p.getCpsn_number().trim(), p.getCpsn_name().trim()));
            }
        }
    }

    private void initFinProjList() {
        if (finProjModel == null) {
            finProjModel = new ListDataModel<FinancialProject>();
        }
        try {
            List<FinancialProject> finli = finProjdao.queryAll(new FinancialProject(true));
            finProjModel.setWrappedData(finli);
        } catch (SQLException ex) {
            Logger.getLogger(FinancialProjectBean.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    //选择预算项目

    public void projSelected() {
        finProj = finProjModel.getRowData();
        exp.getProject().setFinCode(finProj.getFinCode());
        exp.getProject().setFinName(finProj.getFinName());
        exp.getProject().setCostType(finProj.getCostType());
    }

    public void payStyleChange(ValueChangeEvent value) {
        String code = (String) value.getNewValue();
        if (Null.check(code)) return;
        String name = AbroadGroupImpl.getPayStyleName(code);
        exp.getPayStyle().setCode(code);
        exp.getPayStyle().setName(name);
    }

    public void getFirst() {
        if (linkedli.size() == 0) {
            if (expenselist.isEmpty()) {
                saveOrNot = true;
                addOrUpdate = true;
                deleteable = true;
                updateOrNot = true;
                submitOrNot = true;
                showAble = true;
                printAble = true;
                dis.setLast(true);
                dis.setNext(true);
                dis.setPreviouse(true);
                dis.setFirst(true);
                //System.out.println("您尚未录入单据!");
                ToolKit.msgs_info("您尚未录入单据");
                FacesContext.getCurrentInstance().renderResponse();
            } else {
                linkedli.clear();
                linkedli.addAll(expenselist);
                this.setExp(linkedli.getFirst());
                queryPerLi();
                dis.setLast(false);
                dis.setNext(false);
                dis.setPreviouse(true);
                dis.setFirst(true);
                saveOrNot = true;
                showAble = true;
                updateOrNot = false;
                deleteable = false;
                submitOrNot = false;
                printAble = false;
            }
        } else {
            this.setExp(linkedli.getFirst());
            queryPerLi();
            dis.setLast(false);
            dis.setNext(false);
            dis.setPreviouse(true);
            dis.setFirst(true);
            saveOrNot = true;
            showAble = true;
            updateOrNot = false;
            deleteable = false;
            submitOrNot = false;
            printAble = false;
            browAble = true;
        }

        index = 0;
        FacesContext.getCurrentInstance().renderResponse();
    }

    public void getLast() {
        if (linkedli.size() == 0) {
            if (expenselist.isEmpty()) {
                //System.out.println("您尚未录入单据!");
                ToolKit.msgs_info("您尚未录入单据");
                saveOrNot = true;
                addOrUpdate = true;
                deleteable = true;
                updateOrNot = true;
                submitOrNot = true;
                showAble = true;
                printAble = true;
                dis.setLast(true);
                dis.setNext(true);
                dis.setPreviouse(true);
                dis.setFirst(true);
                FacesContext.getCurrentInstance().renderResponse();
            } else {
                linkedli.clear();
                linkedli.addAll(expenselist);
                this.setExp(linkedli.getLast());
                queryPerLi();
                submitOrNot = false;
                dis.setLast(true);
                dis.setNext(true);
                dis.setPreviouse(false);
                dis.setFirst(false);
                saveOrNot = true;
                showAble = true;
                updateOrNot = false;
                deleteable = false;
                printAble = false;
                browAble = true;
            }
        } else {
            this.setExp(linkedli.getLast());
            queryPerLi();
            submitOrNot = false;
            dis.setLast(true);
            dis.setNext(true);
            dis.setPreviouse(false);
            dis.setFirst(false);
            saveOrNot = true;
            showAble = true;
            updateOrNot = false;
            deleteable = false;
            printAble = false;
        }

        index = linkedli.size() - 1;
        FacesContext.getCurrentInstance().renderResponse();
    }

    public void next() {
        if (index < linkedli.size() - 1) {
            index = index + 1;
            this.setExp(linkedli.get(index));
            queryPerLi();
            //System.out.println("this index:" + index);
            dis.setFirst(false);
            dis.setPreviouse(false);
        } else {
            ToolKit.msgs_info("没有了");
            dis.setLast(true);
            dis.setNext(true);
            dis.setFirst(false);
            dis.setPreviouse(false);
            FacesContext.getCurrentInstance().renderResponse();
        }
        submitOrNot = false;
        saveOrNot = true;
        showAble = true;
        updateOrNot = false;
        deleteable = false;
        printAble = false;
        browAble = true;
        FacesContext.getCurrentInstance().renderResponse();
    }

    public void previouse() {
        if (index > 0) {
            index = index - 1;
            this.setExp(linkedli.get(index));
            queryPerLi();
            dis.setNext(false);
            dis.setLast(false);
            //System.out.println("this index:" + index);
        } else {
            //System.out.println("没有了!");
            ToolKit.msgs_info("没有了");
            dis.setFirst(true);
            dis.setPreviouse(true);
            dis.setNext(false);
            dis.setLast(false);
            FacesContext.getCurrentInstance().renderResponse();
        }
        submitOrNot = false;
        saveOrNot = true;
        showAble = true;
        updateOrNot = false;
        deleteable = false;
        printAble = false;
        browAble = true;
        FacesContext.getCurrentInstance().renderResponse();
    }

    public void add() {
        saveOrNot = false;
        printAble = true;
        addOrUpdate = true;
        deleteable = true;
        updateOrNot = true;
        submitOrNot = true;
        showAble = false;
        browAble = false;
        dis.setFirst(true);
        dis.setPreviouse(true);
        dis.setNext(true);
        dis.setLast(true);

        this.setExp(new Expense());
        exp.getUser().setCpsn_name(curPerName().trim());
        exp.getDept().setName(curDeptName().trim());
        exp.getPayDept().setCode(curDeptCode().trim());
        exp.getPayDept().setName(curDeptName().trim());
        exp.setNumDate(curLoginDate());
        //exp.setNumber(ToolsMethed.getMaxNumber());
        exp.setIsQuota("非限额");
        exp.getFeePer().setCpsn_number(curPerNum().trim());
        exp.getFeePer().setCpsn_name(curPerName());
    }

    public void save() {
        if (addOrUpdate) {
            //System.out.println("进入保存");
            exp.setVoutype("3");
            exp.getUser().setCpsn_number(curPerNum().trim());
            exp.getDept().setCode(curDeptCode().trim());
            LoanBillImpl.insertLoanBillVoucher(exp);

        }
        if (!addOrUpdate) {
            //System.out.println("进入修改操作！");
            exp.setNumberStatus("1");
            LoanBillImpl.updateLoanBill(exp);
        }
        saveOrNot = true;       //saveOrNot:   true  保存不可用
        deleteable = false;      //deleteable: false 删除可用
        updateOrNot = false;     //updateOrNot: false 修改可用
        submitOrNot = false;     //submitOrNot: false 提交可用
        showAble = true;        //showAble: true 展示不可用
        printAble = false;       //printAble: false 打印可用
        browAble = true;
        addOrUpdate = false;
        initList();
        ToolKit.msgs_info("请点击【提交】按钮提交单据并打印本单据!");
    }

    public void submitBill() {
        IbatisTemplate.update(nameSpace + "updateExpStatus", exp);
        //删除历史审核信息
        VouCheckInfo info = new VouCheckInfo();
        info.setBillNum(exp.getNumber());
        info.setVouType(exp.getVoutype());
        VoucherPubImpl.deleteCheckInfo(info);

        initStatus();
        exp.setNumberStatus("0");
        showAble = true;
        browAble = true;
        addOrUpdate = true;
        ToolKit.msgs_info("单据已提交成功，等待审核!");
    }

    public void rescind() {
        //IbatisTemplate.update("voucherRescind", exp);
        Map map = new HashMap();
        map.put("orgCode", curOrgCode().trim());
        map.put("voutype", exp.getVoutype().trim());
        map.put("number", exp.getNumber().trim());
        IbatisTemplate.update("commOper.rescindVoucher", map);
        initStatus();
        exp.setNumberStatus("1");
        deleteable = false;
        updateOrNot = false;
        submitOrNot = false;
        //NavigationTool.getSelectedUrl("/reports/person/queryloanbill.xhtml");      
        FacesContext.getCurrentInstance().renderResponse();
    }

    public void update() {
        showAble = false;
        addOrUpdate = false;
        saveOrNot = false;
        browAble = true;
        FacesContext.getCurrentInstance().renderResponse();
    }

    public void delete() {
        IbatisTemplate.delete(nameSpace + "deleLoanBill", exp);
        this.setExp(new Expense());
        initList();
        FacesContext.getCurrentInstance().renderResponse();
    }

    public void show() {
        exp = ((Expense) expenseModel.getRowData());
        queryPerLi();
        index = this.expenseModel.getRowIndex();
        linkedli.clear();
        linkedli.addAll(expenselist);
        submitOrNot = false;
        printAble = false;
        deleteable = false;
        updateOrNot = false;
        showAble = true;
        addOrUpdate = false;
        saveOrNot = true;
        if (index == 0) {
            dis.setFirst(true);
            dis.setPreviouse(true);
            dis.setNext(false);
            dis.setLast(false);
        }
        if (index > 0 && index < linkedli.size() - 1) {
            dis.setFirst(false);
            dis.setLast(false);
            dis.setNext(false);
            dis.setPreviouse(false);
        }
        if (index == linkedli.size() - 1) {
            dis.setLast(true);
            dis.setNext(true);
            dis.setPreviouse(false);
            dis.setFirst(false);
        }
        expenseModel.setWrappedData(new ArrayList<Expense>());
        NavigationTool.getSelectedUrl("/page/pay/business/person/loanbill.xhtml");
        FacesContext.getCurrentInstance().renderResponse();
        //return "main";
    }

    public void cancel() {
        exp = new Expense();
        qlb = new QueryVouchers();
        initStatus();
        if (linkedli.size() > 0) {
            dis.setFirst(false);
            dis.setLast(false);
        }
        FacesContext.getCurrentInstance().renderResponse();
    }

    public void checkandRep() {
        projParam = "1";
        String paramValue = BusinessParameterImpl.queryParamValue(projParam.trim());//1、必填 0、可不必须填写       
        if (exp.getAffair().length() == 0) {
            ToolKit.msgs_err("您还没有输入借款事由!");
        } else if (exp.getTotal() == null || exp.getTotal() == 0d) {
            ToolKit.msgs_err("您想借0元？");
        } else if (Null.check(exp.getProject().getFinCode()) && paramValue.equals("1")) {
            ToolKit.msgs_err("请选择预算项目!");
        } else if (Null.check(exp.getFeePer().getCpsn_number())) {
            ToolKit.msgs_err("请选择借款人!");
        } else if (Null.check(exp.getIsQuota())) {
            ToolKit.msgs_err("请选择是否限额!");
        } else if (Null.check(exp.getPayStyle().getCode().trim())) {
            ToolKit.msgs_err("请选择支付方式!");
        } else {
            save();
        }
    }
    //选择预算项目

    public void selectProjForQuery() {
        FinancialProject fProj = finProjModel.getRowData();
        qlb.getProject().setFinCode(fProj.getFinCode());
        qlb.getProject().setFinName(fProj.getFinName());
        //System.out.println("projcode:" + qlb.getProject().getFinCode().trim());
    }

    public void queryloanbillForPerson() {
        Map map = new HashMap();
        map.put("cpsn_number", curPerNum().trim());
        map.put("orgCode", curOrgCode().trim());
        map.put("number", qlb.getNumber().trim());
        map.put("affair", qlb.getAffair().trim());
        map.put("projcode", qlb.getProject().getFinCode());
        map.put("memo", qlb.getMemo().trim());
        map.put("numDateStart", qlb.getNumDateStart());
        map.put("numDateEnd", qlb.getNumDateEnd());
        map.put("auditDateStart", qlb.getAuditDateStart());
        map.put("auditDateEnd", qlb.getAuditDateEnd());
        map.put("payDateStart", qlb.getPayDateStart());
        map.put("payDateEnd", qlb.getPayDateEnd());
        map.put("totalStart", qlb.getTotalStart());
        map.put("totalEnd", qlb.getTotalEnd());
        map.put("checkaccountStart", qlb.getCheckaccountStart());
        map.put("checkaccountEnd", qlb.getCheckaccountEnd());
        map.put("payaccountStart", qlb.getPayaccountStart());
        map.put("payaccountEnd", qlb.getPayaccountEnd());
        expenselist = IbatisTemplate.queryForList(nameSpace + "loanbillqueryForPerson", map);
        expenseModel.setWrappedData(expenselist);
        //System.out.println("expenselist size:" + expenselist.size());        
    }

    public void clearQueryResult(ActionEvent e) {
        expenseModel.setWrappedData(new ArrayList<Expense>());
    }

    public void print() throws Exception {
        Map map = reportParameter();//parameters

        FacesContext facesContext = FacesContext.getCurrentInstance();
        facesContext.responseComplete();

        ServletContext scontext = (ServletContext) facesContext.getExternalContext().getContext();
        JasperPrint jasperPrint = JasperFillManager.fillReport(scontext.getRealPath("/page/pay/print/loan.jasper"), map);

        // PrintRequestAttributeSet printRequestAttributeSet = new HashPrintRequestAttributeSet();
        //printRequestAttributeSet.add(MediaSizeName.ISO_A5);// 处方模板是A5纸  第一个参数对象

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        JRPdfExporter exporter = new JRPdfExporter();
        exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
        exporter.setParameter(JRExporterParameter.OUTPUT_STREAM, baos);
        exporter.exportReport();
        byte[] bytes = baos.toByteArray();

        if (bytes != null && bytes.length > 0) {
            HttpServletResponse response = (HttpServletResponse) facesContext.getExternalContext().getResponse();
            response.setContentType("application/pdf");
            response.setHeader("Content-disposition", "inline; filename=\"relatorioPorData.pdf\"");
            response.setContentLength(bytes.length);
            ServletOutputStream outputStream = response.getOutputStream();
            outputStream.write(bytes, 0, bytes.length);
            outputStream.flush();
            outputStream.close();
        }
    }

    public void printSinglePage() throws Exception {
        Map map = reportParameter();//parameters
        ArrayList jasperPrintList = new ArrayList();
        FacesContext facesContext = FacesContext.getCurrentInstance();
        facesContext.responseComplete();
        //A4 单据+粘贴单
        ServletContext scontext = (ServletContext) facesContext.getExternalContext().getContext();
        JasperPrint jasperPrint = JasperFillManager.fillReport(scontext.getRealPath("/page/pay/print/loan.jasper"), map);
        jasperPrintList.add(jasperPrint);
//        JasperPrint jasperPrintBill = JasperFillManager.fillReport(scontext.getRealPath("/page/pay/print/bill.jasper"), map);
//        jasperPrintList.add(jasperPrintBill);

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        JRPdfExporter exporter = new JRPdfExporter();
        //exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
        //exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrintList);
        exporter.setParameter(JRExporterParameter.JASPER_PRINT_LIST, jasperPrintList);

        exporter.setParameter(JRExporterParameter.OUTPUT_STREAM, baos);
        exporter.exportReport();
        byte[] bytes = baos.toByteArray();

        if (bytes != null && bytes.length > 0) {
            HttpServletResponse response = (HttpServletResponse) facesContext.getExternalContext().getResponse();
            response.setContentType("application/pdf");
            response.setHeader("Content-disposition", "inline; filename=\"relatorioPorData.pdf\"");
            response.setContentLength(bytes.length);
            ServletOutputStream outputStream = response.getOutputStream();
            outputStream.write(bytes, 0, bytes.length);
            outputStream.flush();
            outputStream.close();
        }
    }

    public void process(OutputStream outStream, Object data) throws Exception {
        printSinglePage();
    }

    private Map reportParameter() {
        Map map = new HashMap();
        map.put("number", exp.getNumber());
        map.put("numDate", exp.getNumDate());
        map.put("deptname", exp.getDept().getName());
        map.put("cpsn_name", exp.getUser().getCpsn_name());
        map.put("affair", exp.getAffair());
        map.put("costType", exp.getCostType());
        map.put("name", exp.getPayStyle().getName());
        map.put("ticketcode", exp.getTicketcode());
        map.put("paycode", exp.getPaycode());
        map.put("money", MoneyUtil.toChinese(String.valueOf(Null.convert(exp.getTotal() == null ? 0d : exp.getTotal()))));
        map.put("total", exp.getTotal());
        map.put("affixAmount", exp.getAffixAmount());

        String costType = isBaseCost();

        System.out.println("costType : [" + costType + "]");
        System.out.println("proj costType : " + exp.getProject().getCostType());
        System.out.println("exp costType : " + exp.getCostType());

        map.put("isBaseCost", costType);//是基本支出 0:基本支出 1：项目支出

        return map;
    }

    private String isBaseCost() {
        if (exp.getProject().getCostType() == 1) return "1";
        else if (exp.getProject().getCostType() == 0) return "0";
        else return "";
    }

    public void exportExcel() {
        HSSFWorkbook demoWorkBook = new HSSFWorkbook();
        HSSFSheet demoSheet = demoWorkBook.createSheet("个人单据借款单列表");
        String[] excelColumns = initTabeleHeader();
        List<Expense> rows = expenselist;

        HSSFHeader header = demoSheet.getHeader();
        header.setCenter("个人单据借款单列表");
        HSSFRow headerRow = demoSheet.createRow(0);
        for (int i = 0; i < excelColumns.length; i++) {
            HSSFCell headerCell = headerRow.createCell((short) i);
            //headerCell.setEncoding(HSSFCell.ENCODING_UTF_16);
            headerCell.setCellValue(excelColumns[i]);
        }
        //填充数据
        int rowIndex = 1;
        for (Expense row : rows) {
            createTableRow(demoWorkBook, demoSheet, row, rowIndex);
            rowIndex++;
        }
        LoanInputBean.exportExcel(demoWorkBook, demoSheet);

    }
    //初始化表头信息

    public String[] initTabeleHeader() {
        String[] excelColumns = {"单据编号", "单据状态", "单据日期", "借款事由", "借款金额", "预算项目", "备注", "核定金额",
            "审核日期", "审核人", "支付金额", "支付方式", "支付日期", "出纳"};
        return excelColumns;
    }

    public static void createTableRow(HSSFWorkbook demoWorkBook, HSSFSheet demoSheet, Expense eil, int rowIndex) {
        //创建第rowIndex行
        //HSSFWorkbook workbook = new HSSFWorkbook();
        CreationHelper createHelper = demoWorkBook.getCreationHelper();
        HSSFCellStyle dstyle = demoWorkBook.createCellStyle();
        dstyle.setDataFormat(createHelper.createDataFormat().getFormat("yyyy-mm-dd"));//格式

        HSSFCell cell;
        HSSFRow row = demoSheet.createRow(rowIndex);
        cell = row.createCell(0);
        cell.setCellValue(PayCodeConstants.convertString(eil.getNumber()));
        cell = row.createCell(1);
        cell.setCellValue(PayCodeConstants.convertString(PayCodeConstants.functionNumberStatus().get(eil.getNumberStatus())));
        cell = row.createCell(2);
        cell.setCellValue(PayCodeConstants.convertDate(eil.getNumDate()));
        cell.setCellStyle(dstyle);
        cell = row.createCell(3);
        cell.setCellValue(PayCodeConstants.convertString(eil.getAffair()));
        cell = row.createCell(4);
        cell.setCellValue(PayCodeConstants.convertDouble(eil.getTotal()));
        cell = row.createCell(5);
        cell.setCellValue(PayCodeConstants.convertString(eil.getProject().getFinName()));
        cell = row.createCell(6);
        cell.setCellValue(PayCodeConstants.convertString(eil.getMemo()));
        cell = row.createCell(7);
        cell.setCellValue(PayCodeConstants.convertDouble(eil.getCheckaccount()));
        cell = row.createCell(8);
        if (eil.getAuditDate() == null) {
            cell.setCellValue("");
        } else {
            cell.setCellValue(PayCodeConstants.convertDate(eil.getAuditDate()));
            cell.setCellStyle(dstyle);
        }
        cell = row.createCell(9);
        cell.setCellValue(PayCodeConstants.convertString(eil.getAuditor()));
        cell = row.createCell(10);
        cell.setCellValue(PayCodeConstants.convertDouble(eil.getPayaccount()));
        cell = row.createCell(11);
        cell.setCellValue(PayCodeConstants.convertString(eil.getPayStyle().getCode()));
        cell = row.createCell(12);
        if (eil.getPayDate() == null) {
            cell.setCellValue("");
        } else {
            cell.setCellValue(PayCodeConstants.convertDate(eil.getPayDate()));
            cell.setCellStyle(dstyle);
        }
        cell = row.createCell(13);
        cell.setCellValue(PayCodeConstants.convertString(eil.getPayer()));

    }

    public static void exportExcel(HSSFWorkbook demoWorkBook, HSSFSheet demoSheet) {
        try {
            String strfileName = "book.xls";
            FileOutputStream fos;
            //导出
            demoSheet.setGridsPrinted(true);//demoSheet
            HSSFFooter footer = demoSheet.getFooter();
            footer.setRight("Page " + HSSFFooter.page() + " of " + HSSFFooter.numPages());
            // 获得JSF上下文环境
            FacesContext context = FacesContext.getCurrentInstance();
            // 获得ServletContext对象
            ServletContext servletContext = (ServletContext) context.getExternalContext().getContext();
            // 取得文件的绝对路径
            String excelName = servletContext.getRealPath("/upload") + "/" + strfileName;//strfileName
            File exportFile = new File(excelName);
            fos = new FileOutputStream(exportFile);//fos
            demoWorkBook.write(fos);//demoWorkBook
            fos.close();

            FacesContext ctx = FacesContext.getCurrentInstance();
            ctx.responseComplete();
            HttpServletResponse httpServletResponse = (HttpServletResponse) ctx.getExternalContext().getResponse();
            ServletOutputStream servletOutputStream = httpServletResponse.getOutputStream();
            httpServletResponse.setHeader("Content-disposition", "attachment; filename=" + strfileName);//strfileName
            httpServletResponse.setContentLength((int) exportFile.length());//exportFile
            httpServletResponse.setContentType("application/x-download");
            //httpServletResponse.setContentType("application/vnd.ms-excel");
            byte[] b = new byte[1024];
            int i;
            FileInputStream fis = new java.io.FileInputStream(exportFile);
            while ((i = fis.read(b)) > 0) {
                servletOutputStream.write(b, 0, i);
            }
            servletOutputStream.flush();
            ctx.responseComplete();
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
    }

    public boolean isAddOrUpdate() {
        return addOrUpdate;
    }

    public void setAddOrUpdate(boolean addOrUpdate) {
        this.addOrUpdate = addOrUpdate;
    }

    public boolean isDeleteable() {
        return deleteable;
    }

    public void setDeleteable(boolean deleteable) {
        this.deleteable = deleteable;
    }

    public List<Expense> getExpenselist() {
        return expenselist;
    }

    public void setExpenselist(List<Expense> expenselist) {
        this.expenselist = expenselist;
    }

    public boolean isPrintAble() {
        return printAble;
    }

    public void setPrintAble(boolean printAble) {
        this.printAble = printAble;
    }

    public QueryVouchers getQlb() {
        return qlb;
    }

    public void setQlb(QueryVouchers qlb) {
        this.qlb = qlb;
    }

    public boolean isSaveOrNot() {
        return saveOrNot;
    }

    public void setSaveOrNot(boolean saveOrNot) {
        this.saveOrNot = saveOrNot;
    }

    public boolean isShowAble() {
        return showAble;
    }

    public void setShowAble(boolean showAble) {
        this.showAble = showAble;
    }

    public boolean isSubmitOrNot() {
        return submitOrNot;
    }

    public void setSubmitOrNot(boolean submitOrNot) {
        this.submitOrNot = submitOrNot;
    }

    public boolean isUpdateOrNot() {
        return updateOrNot;
    }

    public void setUpdateOrNot(boolean updateOrNot) {
        this.updateOrNot = updateOrNot;
    }

    public Expense getExp() {
        return exp;
    }

    public void setExp(Expense exp) {
        this.exp = exp;
    }

    public Disabled getDis() {
        return dis;
    }

    public void setDis(Disabled dis) {
        this.dis = dis;
    }

    public List<SelectItem> getPayStyleli() {
        return payStyleli;
    }

    public void setPayStyleli(List<SelectItem> payStyleli) {
        this.payStyleli = payStyleli;
    }
    //

    private String curPerNum() {
        return LoginParam.getPer().getCpsn_number();
    }

    private String curPerName() {
        return LoginParam.getPer().getCpsn_name();
    }

    private String curDeptCode() {
        return LoginParam.getDept().getCode();
    }

    private String curDeptName() {
        return LoginParam.getDept().getName();
    }

    private Date curLoginDate() {
        return LoginParam.getLoginDate();
    }

    private Integer curIyear() {
        return LoginParam.getIyear();
    }

    private String curOrgCode() {
        return LoginParam.getOrg().getCode();
    }

    public boolean isBrowAble() {
        return browAble;
    }

    public void setBrowAble(boolean browAble) {
        this.browAble = browAble;
    }

    public List<Department> getDeptli() {
        return deptli;
    }

    public void setDeptli(List<Department> deptli) {
        this.deptli = deptli;
    }

    public DataModel<Expense> getExpenseModel() {
        return expenseModel;
    }

    public void setExpenseModel(DataModel<Expense> expenseModel) {
        this.expenseModel = expenseModel;
    }

    public int getIndex() {
        return index;
    }

    public void setIndex(int index) {
        this.index = index;
    }

    public LinkedList<Expense> getLinkedli() {
        return linkedli;
    }

    public void setLinkedli(LinkedList<Expense> linkedli) {
        this.linkedli = linkedli;
    }

    public UIDataTable getDeptData() {
        return deptData;
    }

    public void setDeptData(UIDataTable deptData) {
        this.deptData = deptData;
    }

    public UIDataTable getPersonData() {
        return personData;
    }

    public void setPersonData(UIDataTable personData) {
        this.personData = personData;
    }

    public FinancialProject getFinProj() {
        return finProj;
    }

    public void setFinProj(FinancialProject finProj) {
        this.finProj = finProj;
    }

    public DataModel<FinancialProject> getFinProjModel() {
        return finProjModel;
    }

    public void setFinProjModel(DataModel<FinancialProject> finProjModel) {
        this.finProjModel = finProjModel;
    }

    public String getProjParam() {
        return projParam;
    }

    public void setProjParam(String projParam) {
        this.projParam = projParam;
    }

    public List<SelectItem> getPerli() {
        if (perli == null) queryPerLi();
        return perli;
    }

    public void setPerli(List<SelectItem> perli) {
        this.perli = perli;
    }
}
